package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.Bestseller;
import com.bookstore.back.entity.Book;
import com.bookstore.back.mapper.BestsellerMapper;
import com.bookstore.back.mapper.BookMapper;
import com.bookstore.back.service.BestsellerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 畅销榜单服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-23
 */
@Service
public class BestsellerServiceImpl extends ServiceImpl<BestsellerMapper, Bestseller> implements BestsellerService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public IPage<Bestseller> getBestsellerList(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

        // 查询条件
        QueryWrapper<Bestseller> queryWrapper = new QueryWrapper<>();

        String categoryIdStr = (String) params.get("categoryId");
        if (StringUtils.isNotBlank(categoryIdStr)) {
            Integer categoryId = Integer.parseInt(categoryIdStr);
            queryWrapper.eq("category_id", categoryId);
        } else {
            // 如果没有指定分类，默认查询综合榜（category_id = -1）
            queryWrapper.eq("category_id", -1);
        }

        String period = (String) params.get("period");
        if (StringUtils.isNotBlank(period)) {
            queryWrapper.eq("period", period);
        }
        queryWrapper.orderByAsc("rank");

        List<Bestseller> allBestsellers = this.list(queryWrapper);
        for (Bestseller bestseller : allBestsellers) {
            Book book = bookMapper.selectById(bestseller.getBookId());
            bestseller.setBook(book);
        }

        List<Bestseller> filteredList = allBestsellers;
        String title = (String) params.get("title");
        if (StringUtils.isNotBlank(title)) {
            filteredList = filteredList.stream()
                .filter(bestseller -> bestseller.getBook() != null &&
                       bestseller.getBook().getTitle() != null &&
                       bestseller.getBook().getTitle().contains(title))
                .collect(java.util.stream.Collectors.toList());
        }

        int total = filteredList.size();
        int startIndex = (current - 1) * size;
        int endIndex = Math.min(startIndex + size, total);

        List<Bestseller> pagedList = startIndex < total ?
            filteredList.subList(startIndex, endIndex) :
            new ArrayList<>();

        // 创建分页结果
        IPage<Bestseller> page = new Page<>(current, size, total);
        page.setRecords(pagedList);

        return page;
    }

    @Override
    @Transactional
    public boolean createBestseller(Bestseller bestseller) {
        // 检查是否已存在相同的记录
        QueryWrapper<Bestseller> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", bestseller.getBookId())
                   .eq("category_id", bestseller.getCategoryId())
                   .eq("period", bestseller.getPeriod());
        
        Bestseller existing = this.getOne(queryWrapper);
        if (existing != null) {
            throw new RuntimeException("该图书在此分类和周期下已存在于畅销榜中");
        }
        
        // 检查排名是否已被占用
        QueryWrapper<Bestseller> rankWrapper = new QueryWrapper<>();
        rankWrapper.eq("category_id", bestseller.getCategoryId())
                  .eq("period", bestseller.getPeriod())
                  .eq("rank", bestseller.getRank());
        
        Bestseller existingRank = this.getOne(rankWrapper);
        if (existingRank != null) {
            // 如果排名已被占用，将后续排名都往后移一位
            QueryWrapper<Bestseller> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("category_id", bestseller.getCategoryId())
                        .eq("period", bestseller.getPeriod())
                        .ge("rank", bestseller.getRank());
            
            List<Bestseller> toUpdate = this.list(updateWrapper);
            for (Bestseller item : toUpdate) {
                item.setRank(item.getRank() + 1);
                this.updateById(item);
            }
        }
        
        return this.save(bestseller);
    }

    @Override
    public boolean updateBestseller(Integer bestsellerId, Bestseller bestseller) {
        bestseller.setId(bestsellerId);
        return this.updateById(bestseller);
    }

    @Override
    public boolean deleteBestseller(Integer bestsellerId) {
        return this.removeById(bestsellerId);
    }

    @Override
    @Transactional
    public boolean updateBestsellerRanks(List<Map<String, Object>> rankUpdates) {
        try {
            for (Map<String, Object> update : rankUpdates) {
                Integer id = (Integer) update.get("id");
                Integer rank = (Integer) update.get("rank");
                
                Bestseller bestseller = new Bestseller();
                bestseller.setId(id);
                bestseller.setRank(rank);
                this.updateById(bestseller);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("批量更新排名失败：" + e.getMessage());
        }
    }

    @Override
    public List<Book> getAvailableBooks(Map<String, Object> params) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        
        // 只查询上架的图书
        queryWrapper.eq("status", 1);
        
        // 标题搜索
        String title = (String) params.get("title");
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like("title", title);
        }
        
        // 按销量倒序
        queryWrapper.orderByDesc("sales");
        
        // 限制返回数量
        queryWrapper.last("LIMIT 50");
        
        return bookMapper.selectList(queryWrapper);
    }

}
